<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="地图"
      width="800"
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="map">
        <AmapUI ref="amapUIRef" :opts="opts" :modules="modules"></AmapUI>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { AmapUI, coordinateConverter } from "@zszc/co-amapui-v3";

const emit = defineEmits(["submit"]);

const dialogVisible = ref(false);

const type = ref("");
const openMap = params => {
  type.value = params;
  dialogVisible.value = true;
  modules.value = [
    {
      name: "Geocoder",
      markers: {}
    }
  ];
  nextTick(() => {
    amapUIRef.value?.loadModules();
  });
};

// 地图配置
const opts = reactive<any>({
  center: [116.397428, 39.90923],
  zoom: 4
});

const modules = ref<any[]>([]);

const amapUIRef = ref<InstanceType<typeof AmapUI> | null>(null);
onMounted(() => {
  console.log("地图加载");
});

const handleSubmit = () => {
  dialogVisible.value = false;

  // 获取模块
  const GeoCoder = amapUIRef.value?.getModule("Geocoder");
  if (!GeoCoder) {
    return;
  }

  const LngLat = GeoCoder.moduleInstance?.events.getLnglat() || [];

  // 坐标转换
  if (LngLat.length === 0) {
    return;
  }

  // 坐标转换
  const WGS84lnglat = coordinateConverter.gcj02ToWgs84(LngLat[0], LngLat[1]);
  // 截取到7位小数
  const formattedlnglat = {
    lng: parseFloat(WGS84lnglat[0].toFixed(7)),
    lat: parseFloat(WGS84lnglat[1].toFixed(7))
  };
  emit("submit", {
    lnglat: formattedlnglat,
    type: type.value
  });
};

defineExpose({
  openMap
});
</script>

<style scoped>
.map {
  width: 100%;
  height: 450px;
}
</style>
